from django.shortcuts import render

from rest_framework.filters import OrderingFilter
from django_filters.rest_framework import DjangoFilterBackend

# Create your views here.

from rest_framework.viewsets import GenericViewSet
from utils.common_mixin import CommonListModelMixin
from utils.qiuniu_file import upload_qiniu_file
from . import models
from .pagination import CommonPagination
from .serializer import CourseCategorySerializer, CourseSerializer, CourseChapterSerializer

from utils.common_mixin import CommonListModelMixin as ListModelMixin
from utils.common_mixin import CommonRetrieveModelMixin as RetrieveModelMixin


class CourseCategoryView(GenericViewSet, CommonListModelMixin):
    """
    课程分类
    """
    queryset = models.CourseCategory.objects.filter(is_delete=False, is_show=True)
    serializer_class = CourseCategorySerializer

    # def get(self, request, *args, **kwargs):
    #     return self.list(request, *args, **kwargs)


class CourseView(GenericViewSet, ListModelMixin, RetrieveModelMixin):
    queryset = models.Course.objects.filter(is_delete=False, is_show=True).order_by('orders')
    serializer_class = CourseSerializer
    pagination_class = CommonPagination
    # 排序,过滤课程分类（course_category=2）
    filter_backends = [OrderingFilter, DjangoFilterBackend]
    ordering_fields = ['students', 'price']
    filterset_fields = ['course_category']


class CourseChapterView(GenericViewSet, CommonListModelMixin):
    """
    课程章节
    """
    serializer_class = CourseChapterSerializer
    queryset = models.CourseChapter.objects.filter(is_delete=False, is_show=True).order_by('orders')
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ['course']  # 按课程过滤


from rest_framework.views import APIView

from utils.common_response import APIResponse

from django.conf import settings
import os


class UploadFile(APIView):
    """
    上传文件
    """

    def post(self, request, *args, **kwargs):
        file = request.FILES.get('file')
        base_url = os.path.dirname(settings.BASE_DIR)

        end_path = os.path.join(base_url, 'media', 'temp_upload', file.name)
        # 上传代码开始
        destination = open(end_path, 'wb+')  # 打开特定的文件进行二进制的写操作
        for chunk in file.chunks():  # 分块写入文件
            destination.write(chunk)
        destination.close()
        ###上传代码结束
        # 上传到七牛云
        upload_qiniu_file(key='1.log', localfile=end_path, bucket_name='ymq-text')
        return APIResponse()


from rest_framework.filters import SearchFilter


class SearchCourseView(GenericViewSet, CommonListModelMixin):
    serializer_class = CourseSerializer
    queryset = models.Course.objects.filter(is_delete=False, is_show=True).order_by('orders')
    filter_backends = [SearchFilter]
    search_fields = ['name', 'brief']  # 1 brief内容非常多，如果使用mysql的搜索，like 全文搜，随着数据量越来越大，搜索越来越慢---》分布式全文检索引擎elasticsearch
